﻿create PROCEDURE [dbo].[sp_Update_UpdateAgentNumberByUserId]
 @UserId varchar(50),
 @Division varchar(50),
 @Market varchar(50),
 @AgentNum int
AS
 if @Division is not null and @Market is not null
  if exists (select * from DivisionMarket where Division = @Division and Market = @Market and MdNumber = @UserId) 
   update DivisionMarket set AgentCount = @AgentNum
   where Division = @Division and Market = @Market and MdNumber = @UserId
  else
   INSERT INTO [dbo].[DivisionMarket]
       ([Division]
       ,[Market]
       ,[MdNumber]
       ,[AgentCount])
    VALUES
       (@Division
       ,@Market
       ,@UserId
       ,@AgentNum)
 else
  update Accounts set AgentNumber = @AgentNum where AccountID = @UserId;
